﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Castle.Core.Logging;
using ComponentFactory.Krypton.Toolkit;

namespace TVN.ShopMan.ApplicationInterface.AppForms
{
    using TVN.Common.Helpers;
    using TVN.Common.Interfaces;
    using TVN.ShopMan.ActiveModels;

    public partial class AccountForm : Form
    {
        private class ColumnIndex
        {
            public const int Id = 0;
            public const int UserName = 1;
            public const int FullName = 2;
            public const int Password = 3;
            public const int Email = 4;
            public const int IsActive = 5;
        }

        private static readonly ILogger _logger = Program.Logger.CreateChildLogger("AccountForm");
        private IRepository<Account> accountRepository = null;
        private IList<Account> listOfAccounts = null;
        private IList<Account> listOfAccountsToDelete = null;

        #region Constructors

        public AccountForm()
        {
            InitializeComponent();

            this.SetUp();
            this.LoadData();
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Setup the data grid
        /// </summary>
        private void SetUp()
        {
            this.accountRepository = Program.Container.Resolve<IRepository<Account>>();

            this.kdgvAccounts.AutoGenerateColumns = false;
            var idColumn = new DataGridViewColumn
            {
                DataPropertyName = Account.Properties.Id,
                Name = Account.Properties.Id,
                HeaderText = "Id",
                ValueType = typeof(int),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = false,
            };
            this.kdgvAccounts.Columns.Add(idColumn);

            var usernameColumn = new DataGridViewColumn
            {
                DataPropertyName = Account.Properties.Username,
                Name = Account.Properties.Username,
                HeaderText = "User name",
                ValueType = typeof(string),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true,
                MinimumWidth = 100,
            };
            this.kdgvAccounts.Columns.Add(usernameColumn);

            var fullnameColumn = new DataGridViewColumn
            {
                DataPropertyName = Account.Properties.FullName,
                Name = Account.Properties.FullName,
                HeaderText = "Full name",
                ValueType = typeof(string),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true,
                MinimumWidth = 100,
            };
            this.kdgvAccounts.Columns.Add(fullnameColumn);

            var passwordColumn = new DataGridViewColumn
            {
                DataPropertyName = Account.Properties.Password,
                Name = Account.Properties.Password,
                HeaderText = "Password",
                ValueType = typeof(string),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true
            };
            this.kdgvAccounts.Columns.Add(passwordColumn);

            var emailColumn = new DataGridViewColumn
            {
                DataPropertyName = Account.Properties.Email,
                Name = Account.Properties.Email,
                HeaderText = "Email",
                ValueType = typeof(string),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true,
                MinimumWidth = 100,
            };
            this.kdgvAccounts.Columns.Add(emailColumn);

            var isActiveColumn = new DataGridViewColumn
            {
                DataPropertyName = Account.Properties.IsActive,
                Name = Account.Properties.IsActive,
                HeaderText = "Is active",
                ValueType = typeof(bool),
                CellTemplate = new DataGridViewCheckBoxCell(false),
                DefaultCellStyle = new DataGridViewCellStyle
                {
                    Alignment = DataGridViewContentAlignment.MiddleCenter
                },
                Visible = true
            };
            this.kdgvAccounts.Columns.Add(isActiveColumn);
        }

        /// <summary>
        /// Load all accounts from database
        /// </summary>
        private void LoadData()
        {
            this.listOfAccounts = this.accountRepository.FindAll();
            if (this.listOfAccounts == null)
            {
                this.listOfAccounts = new List<Account>();
            }

            foreach (Account accountItem in this.listOfAccounts)
            {
                this.DisplayAccountData(accountItem);
            }
        }

        private void DisplayAccountData(Account accountItem)
        {
            if (accountItem != null)
            {
                this.kdgvAccounts.Rows.Add(accountItem.Id, accountItem.Username, accountItem.FullName,
                                           PasswordHelper.ToString(accountItem.Password), accountItem.Email, accountItem.IsActive);
            }
        }

        private void UpdateAccountData(Account accountItem)
        {
            if (accountItem != null)
            {
                foreach (DataGridViewRow rowItem in this.kdgvAccounts.Rows)
                {
                    if (accountItem.Id.Equals(rowItem.Cells[ColumnIndex.Id].Value)
                        && accountItem.Email.Equals(rowItem.Cells[ColumnIndex.Email].Value))
                    {
                        rowItem.Cells[ColumnIndex.Email].Value = accountItem.Email;
                        rowItem.Cells[ColumnIndex.FullName].Value = accountItem.FullName;
                        rowItem.Cells[ColumnIndex.IsActive].Value = accountItem.IsActive;
                        rowItem.Cells[ColumnIndex.Password].Value = PasswordHelper.ToString(accountItem.Password);
                        rowItem.Cells[ColumnIndex.UserName].Value = accountItem.Username;

                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Add new account into the list and data grid
        /// </summary>
        /// <param name="account"></param>
        private void AddOrUpdateAccount(Account accountItem)
        {
            if (accountItem != null)
            {
                Account existingAccount = this.listOfAccounts.FirstOrDefault(item => ((item.Id == accountItem.Id) || (item.Email == accountItem.Email)));
                if (existingAccount == null)
                {
                    this.listOfAccounts.Add(accountItem);
                    this.DisplayAccountData(accountItem);
                }
                else
                {
                    existingAccount = accountItem;
                    this.UpdateAccountData(accountItem);
                }
            }
        }

        private void ShowAccountForm(DataGridViewRow rowItem)
        {
            if (rowItem != null)
            {
                int accountId = Convert.ToInt32(rowItem.Cells[ColumnIndex.Id].Value);
                string email = Convert.ToString(rowItem.Cells[ColumnIndex.Email].Value);

                Account accountItem = this.listOfAccounts.FirstOrDefault(item => ((item.Id == accountId) && (item.Email == email)));
                using (AccountFormEdit accountForm = new AccountFormEdit(accountItem, AccountFormEdit.EditModes.PasswordFocus)
                {
                    StartPosition = FormStartPosition.CenterParent
                })
                {
                    var result = accountForm.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        this.AddOrUpdateAccount(accountForm.SelectedAccount);
                    }
                }
            }
        }

        private DialogResult ConfirmRemoveAccounts()
        {
            var result = DialogResult.None;

            if (this.kdgvAccounts.SelectedRows.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Are you sure you want to delete these accounts:");
                sb.AppendLine();
                foreach (DataGridViewRow rowItem in this.kdgvAccounts.SelectedRows)
                {
                    sb.AppendFormat("   {0} - {1}", rowItem.Cells[ColumnIndex.UserName].Value, rowItem.Cells[ColumnIndex.FullName].Value);
                    sb.AppendLine();
                }

                result = KryptonMessageBox.Show(sb.ToString(), "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            }

            return result;
        }

        #endregion

        #region Events

        private void btnNewAccount_Click(object sender, EventArgs e)
        {
            using (AccountFormEdit accountForm = new AccountFormEdit()
            {
                StartPosition = FormStartPosition.CenterParent
            })
            {
                var result = accountForm.ShowDialog();
                if (result == DialogResult.OK)
                {
                    this.AddOrUpdateAccount(accountForm.SelectedAccount);
                }
            }
        }

        private void btnSaveChanges_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.listOfAccountsToDelete != null)
                {
                    foreach (Account accountItem in this.listOfAccountsToDelete)
                    {
                        if (accountItem != null)
                        {
                            accountItem.Delete();
                        }
                    }
                }

                if (this.listOfAccounts != null)
                {
                    foreach (Account accountItem in this.listOfAccounts)
                    {
                        accountItem.Save();
                    }
                }

                this.DialogResult = DialogResult.OK;
                this.Close();
                this.Dispose();
                GC.SuppressFinalize(this);
            }
            catch (Exception ex)
            {
                this.DialogResult = DialogResult.No;
                _logger.Error("Error while saving changes", ex);
            }
        }

        private void kdgvAccounts_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            switch (e.ColumnIndex)
            {
                case ColumnIndex.Password:
                    e.Cancel = true;

                    try
                    {
                        this.ShowAccountForm(this.kdgvAccounts.Rows[e.RowIndex]);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Error while preparing account edit form", ex);
                    }

                    break;
            }
        }

        private void kdgvAccounts_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                DataGridViewCell modifiedCell = this.kdgvAccounts.Rows[e.RowIndex].Cells[e.ColumnIndex];

                int accountId = Convert.ToInt32(this.kdgvAccounts.Rows[e.RowIndex].Cells[ColumnIndex.Id].Value);
                Account selectedAccount = this.listOfAccounts.FirstOrDefault(repositoryItem => repositoryItem.Id == accountId);

                switch (e.ColumnIndex)
                {
                    case ColumnIndex.Email:
                        selectedAccount.Email = Convert.ToString(modifiedCell.Value);
                        break;
                    case ColumnIndex.FullName:
                        selectedAccount.FullName = Convert.ToString(modifiedCell.Value);
                        break;
                    case ColumnIndex.IsActive:
                        selectedAccount.IsActive = Convert.ToBoolean(modifiedCell.Value);
                        break;
                    case ColumnIndex.UserName:
                        selectedAccount.Username = Convert.ToString(modifiedCell.Value);
                        break;
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorFormat(ex, "Error while editing cell: {0}", e.ColumnIndex);
            }
        }

        private void kdgvAccounts_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            int accountId = Convert.ToInt32(e.Row.Cells[ColumnIndex.Id].Value);
            string email = Convert.ToString(e.Row.Cells[ColumnIndex.Email].Value);
            Account accountItem = this.listOfAccounts.FirstOrDefault(item => ((item.Id == accountId) && (item.Email == email)));

            if (this.listOfAccountsToDelete == null)
            {
                this.listOfAccountsToDelete = new List<Account>();
            }
            this.listOfAccountsToDelete.Add(accountItem);
            this.listOfAccounts.Remove(accountItem);
        }

        private void kdgvAccounts_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (this.ConfirmRemoveAccounts() != DialogResult.Yes)
            {
                e.Cancel = true;
            }
        }

        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.kdgvAccounts.CurrentRow != null)
                {
                    this.ShowAccountForm(this.kdgvAccounts.CurrentRow);
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error while updating account", ex);
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.ConfirmRemoveAccounts() == DialogResult.Yes)
            {
                foreach (DataGridViewRow rowItem in this.kdgvAccounts.SelectedRows)
                {
                    this.kdgvAccounts.Rows.Remove(rowItem);

                    // Add deleted rows into the list
                    int accountId = Convert.ToInt32(rowItem.Cells[ColumnIndex.Id].Value);
                    string email = Convert.ToString(rowItem.Cells[ColumnIndex.Email].Value);
                    Account accountItem = this.listOfAccounts.FirstOrDefault(item => ((item.Id == accountId) && (item.Email == email)));

                    if (this.listOfAccountsToDelete == null)
                    {
                        this.listOfAccountsToDelete = new List<Account>();
                    }
                    this.listOfAccountsToDelete.Add(accountItem);
                    this.listOfAccounts.Remove(accountItem);
                }
            }
        }

        #endregion

    }
}